//
//  WBAuthController.swift
//  weiboD
//
//  Created by gao2015 on 2016/12/3.
//  Copyright © 2016年 gao2015. All rights reserved.
//

import UIKit
import SVProgressHUD

//新浪微博给我们的唯一标识
let AppKey = "1323857465"
//应用秘钥
let AppSecret = "042bfbf9e5949e75762a243340007835"
//授权回调页
let Redirect_uri = "http://www.youku.com"

class WBAuthController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        loadRequest()
        setupNavUI()
    }
    
    
//    //提供一个方法获取accessToken
//    fileprivate func requestAcessToken(code:String) {
//        //这里的error为啥没类型
//        WBNetworkTool.shareTool.requestAccessToken(code: code, callBack: {(respose:Any?, error) -> () in
//            
//            if error != nil{
//                print("出错了！！！！！！！")
//            }
//            print(respose)
//            //字典转模型
//            let dict = respose as![String : Any]
//            let userCount = WBUserAccount(dic: dict)
//            //给用户信息赋值
//            self.getUserinfo(userAccount: userCount)
//        })
//    }
//    
//    //MARK:提供方法获取userInfo
//    private func getUserinfo(userAccount:WBUserAccount){
//        let uid = userAccount.uid
//        let access_token = userAccount.access_token
//        //response这里是any的话有问题?
//        WBNetworkTool.shareTool.requestGetUserInfo(accessToken: access_token!, uid: uid, callBack: {(response, error) -> () in
//            if error != nil{
////                print(error)
//                return
//            }
////            print(response)
//            //字典转模型
//            let dict = response as! [String:Any]
//            userAccount.name = dict["name"] as? String
//            userAccount.avatar_large = dict["avatar_large"] as? String
//            //将用户信息归档
//            userAccount.saveUserAccount()
//        })
//    }
    
    //懒加载一个webView
    lazy var webView : UIWebView = UIWebView()
    
    //重新布局子控件，让这个webView成为这个控制器的view
    override func loadView() {
        view = webView
        webView.delegate = self
    }
//MARK: 1.加载请求
    
    private func loadRequest(){
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(Redirect_uri)"
        let request = URLRequest(url: URL(string: url)!)
        webView.loadRequest(request)
    }
    
//MARK :2.设置导航控制器
    private func setupNavUI(){
        //让其透明
        webView.isOpaque = false
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFillAction))
        navigationItem.title = "微博登录"
    }
    @objc private func cancelAction(){
        print("取消")
        dismiss(animated: true, completion: nil)
        SVProgressHUD.dismiss()
    }
    @objc private func autoFillAction(){
        print("自动填充")
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = '18210806590'; document.getElementById('passwd').value = '6830561tt'")
    }
}
//MARK:webView的代理方法
extension WBAuthController : UIWebViewDelegate{
    
    
    
    //将要加载请求,可以通过拿到request,navigationType
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool{
        guard let url = request.url else{
            return false
        }
            /*
             //将要进入webView加载一次，点击登录后又加载一次这个方法
             //第一次拿到的url:https://api.weibo.com/oauth2/authorize?client_id=1323857465&redirect_uri=http://www.youku.com我们不需要,
             //第二次是点击登录后拿到的url  https://api.weibo.com/oauth2/authorize
             //需要获取点击授权成功后拿到的url    http://www.youku.com/?code=0e28a54d456d167e32e691305f668734
             //print(url)
             //我们要这个code=0e28a54d456d167e32e691305f668734
             */
        //我们需要判断是不是我们想要的回调页(我设置是优酷那个)
        if !url.absoluteString.hasPrefix(Redirect_uri) {
            //若不是的话则让其执行,让其可以加载
            return true
        }
        
        //此时这个url是我们拿到的url地址,将这个地址分离出code
        if let query = url.query, query.hasPrefix("code=") {
            //query存在且截取到开头是code=的query
            let startInx = "code=".endIndex
            let code = query.substring(from: startInx)
            //code拿到到,需要获取到accessToken,调用我们自己封装的方法
//            requestAcessToken(code: code)
            WBUserAccoutViewModel.shareUserAccout.requestAcessToken(code: code, callBack: { (isSuccess) in
                if isSuccess == true{
                    print("登录成功")
                    //切换到欢迎页面
                    // 分析:通知操作必须在diss之后，否则会持有这个访客视图控制器
                    //由访客视图弹出的是webView的控制器,若没有在diss操作结束后就发通知,会有问题？？？
                    
                    self.dismiss(animated: true, completion: {
                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: SwitchRootViewControllerName), object: self)
                    })
                    
                    
                }else{
                    print("登录失败")
                }
            })
        
        }else{
            print("这里是取消授权的操作")
            self.dismiss(animated: true, completion: nil)
        }
        
        
        
        
        return false
    }
    
    //webView已经开始加载
    func webViewDidStartLoad(_ webView: UIWebView){
        SVProgressHUD .show(withStatus: "正在加载网络请求")
    }
    //webView加载完成后调用
    func webViewDidFinishLoad(_ webView: UIWebView){
        SVProgressHUD.dismiss()
    }
   func webView(_ webView: UIWebView, didFailLoadWithError error: Error){
        SVProgressHUD.dismiss()
    }
}

